<template>
  <!-- Desc：上传图片组件，专注3个地方：初始请求的回填、上传后的回调、提交时的拼接(个别特殊的别用此组件，反而更麻烦) -->
    <div>
      <el-upload
          class="upload-demo"
          ref="upload"
          :limit="limit"
          :action="$BASEAPI + 'Excel/importExcelFile'"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          :on-error="handleError"
          :before-remove="beforeRemove"
          :data="uploadData"
          :file-list="backfillList"
      >
        <el-button slot="trigger" size="mini" type="primary">选取文件</el-button>
      </el-upload>
    </div>
</template>

<script>
import { getToken } from '@/plugins/auth.js';
import { delExcelFile } from '@/api/xapi';
export default {
  props: {
    filelist: {
      type: Array,
      default: () => []
    },
    limit: {
      type: Number,
      default: 1
    },
    listType: {
      type: String,
      default: 'picture-card'
    },
    isShow: {
      type: Boolean,
      default: true
    },
    imgSize: {
      type: String,
      default: 'size148'
    }
  },
  data() {
    return {
      uploadData: {
        // file: '',                                    // -文件名字处理
        token: '',                                   // -七牛token
        admin_id:''
      },
      backfillList: [],                            // -接受父层回显、上传后list同步、删除同步、传给父层
      importAdd:''
    }
  },
  created() {
    this.uploadData.token = String(getToken().split('##')[0]);
    this.uploadData.admin_id = String(getToken().split('##')[1]);
    this.$nextTick(() => { this.init() })
  },
  methods: {
    beforeRemove(file) {
      if(file && file.status === 'success'){
        let filename = file.response.data;
        return this.$confirm('确认删除此数据?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async _ => {
          const { code } = await delExcelFile({ filename: filename })
          if (code === 200) {
            this.$message({ message: '删除成功', type: 'success' });
            this.backfillList = [];
            this.$emit('backList', this.backfillList)
          }
        }).catch(()=>{
          this.$message({
            type: "info",
            message: "已取消删除!"
          });
          reject(false)
        })
      }
      this.$emit('beforeRemove',file)
    },

    /**
     * 2. 上传前：判断
     */
    beforeAvatarUpload(file) {
      const val = file.name;
      if (file.name.indexOf('.xls') !== -1) {
        var suffix = val.substring(val.lastIndexOf('.') + 1, val.length) // -拿到后缀，又把后缀拼回去
        this.uploadData.file = +new Date() + '/' + file.uid + '.' + suffix // -图片改名成时间戳名不容易出BUG
        this.uploadData.fileName = val;
        const isLt2M = file.size / 1024 / 1024 < 50
        if (!isLt2M) {
          this.$message.error('文件大小不能超过 50MB!')
          return false
        }
      } else {
        this.$message.error('只允许上传表格类型的文件!')
        return false
      }
    },

    /**
     * Init. 回填(加载)
     */
    init() {
      this.$nextTick(() => {
        this.backfillList = JSON.parse(JSON.stringify(this.filelist))
      })
    },

    /**
     * 3. 上传后：处理
     */
    handleAvatarSuccess(res, file, list) {
      this.$message({ message: '操作成功', type: 'success',duration:1000 })
      this.backfillList = list.map(item => {
        item.name = item.raw.name;
        item.url = item.response.data.url
        return item
      })
      this.$emit('backList', this.backfillList)
    },
    /**
     * 事件：上传报错
     */
    handleError: function(res) {
      alert(res)
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
